package com.clusterswisdom.horn.api.ioc.struct;

import java.lang.reflect.Method;

import com.alibaba.fastjson.JSONObject;

public class DefaultStructFormatter implements StructFormatter {

	@Override
	public JSONObject format(Object data, StructConfig config) {
		if (config.getDest() == null || config.getDest().getFields() == null || config.getDest().getFields().size() == 0) {
			return (JSONObject)data;
		}
		
		JSONObject formmatData = new JSONObject();
		for (DestField field : config.getDest().getFields()) {
			String mapping = field.getMapping();
			if (mapping == null) {
				mapping = field.getName();
			}
			
			formmatData.put(field.getName(), getObjectPropertyValue(data, mapping));
		}
		
		return formmatData;
	}

	protected Object getObjectPropertyValue(Object data, String mapping) {
		try {
			Method getMethod = data.getClass().getMethod(getGetMethod(mapping));
			return getMethod.invoke(data);
			
		} catch (Exception e) {
			e.printStackTrace();
			
		}
		
		return null;
		
	}
	
	private String getGetMethod(String mapping) {
		return "get" + mapping.substring(0, 1).toUpperCase() + mapping.substring(1);
	}
}
